<?php
namespace app\admin\controller;

use app\admin\model\Config as ConfigModel;
use think\facade\View;
use think\facade\Session;
use think\captcha\facade\Captcha;

/**
 * 商家后台认证
 */
class Passport extends Controller
{
    /**
     * 生成验证码
     **/
    public function captcha()
    {
        return Captcha::create();
    }

    /**
     * 商家用户登录
     */
    public function login()
    {
        if (!$this->request->isAjax()) {
            // 验证登录状态
            if (isset($this->user) AND (int)$this->user['is_login'] === 1) {
                return redirect(url('index/index'));
            }
            View::layout(false);
            return View::fetch();
        }
        $model = new ConfigModel;
        if ($model->login($this->postData('data'))) {
            return $this->renderSuccess('登录成功', url('index/index'));
        }
        $error = $model->getError() ?: '登录失败';
        return $this->renderError($error);
    }

    /**
     * 更新密码
     */
    public function renew()
    {
        $model = ConfigModel::detail();
        if (!$this->request->isAjax()) {
            return View::fetch('renew', compact('model'));            
        }
        if ($model->renew($this->postData('data'))) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        // 清空登录状态
        Session::delete('hema_admin');
        return redirect(url('passport/login'));
    }

}
